package com.kawa.kemanage.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kawa.kemanage.entity.User;
import com.kawa.kemanage.mapper.UserMapper;
import com.kawa.kemanage.service.UserService;
import com.kawa.kemanage.util.JwtUtil;
import com.kawa.kemanage.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, Object> login(String username, String password) {
        // 2. 查询用户
        User user = (User) userMapper.findByUserName(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        // 3. 验证密码
        if (!user.getPassword().equals(password)) {
            throw new RuntimeException("密码错误");
        }
        // 4. 生成token
        String token = JwtUtil.generateToken(Long.valueOf(user.getId()), user.getUserName());
        // 5. 返回登录信息
        Map<String, Object> loginInfo = new HashMap<>();
        loginInfo.put("token", token);
        loginInfo.put("userName", user.getUserName());
        loginInfo.put("userType", user.getUserType());
        return loginInfo;
    }


    /**
     * 根据名字和用户类型查询所有用户
     * @return
     */
    @Override
    public  Result findAllUsers(Integer pageNum, Integer pageSize, String userName, Integer userType) {
        // 1. 分页查询用户
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<User> pageInfo = new PageInfo<>(userMapper.findAllUsers(userName, userType));
        return Result.success(pageInfo);
    }

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    @Override
    public User findUserById(Integer id) {
        User user = userMapper.findUserById(id);
        return user;
    }



    /**
     * 修改用户
     * @param user
     * @return
     */
    @Override
    public int updateUserById(User user) {
        int result = userMapper.updateUserById(user);
        if (result == 1) {
            return 1;
        }else {
            return 0;
        }
    }


    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    @Override
    public int deleteUserById(Integer id) {

        int result = userMapper.deleteUserById(id);
        if (result == 1) {
            return 1;
        }
        return 0;
    }


    /**
     * 新增用户
     * @param user
     * @return
     */
    @Override
    public int insertUser(User user) {
        int result = userMapper.insertUser(user);
        if (result == 1) {
            return 1;
        }
        return 0;
    }


}
